<?php

    class XmlNode
    {
        protected $name;
        protected $attributes;
        protected $data = null;
        protected $brothers = array();

        public function __construct($name, array $attributes)
        {
            $this->name = $name;
            $this->attributes = $attributes;

            $this->brothers[] = $this;
        }

        /**
         * Returns node name.
         *
         * @return string
         */
        public function getName()
        {
            return $this->name;
        }

        /**
         * Returns node attributes.
         *
         * @return array
         */
        public function getAttributes()
        {
            return $this->attributes;
        }

        /**
         * Returns specified attribute.
         * If it doesn't exists returns null.
         *
         * @param string $attribute
         * @return string
         */
        public function getAttribute($attribute)
        {
            return isset($this->attributes[$attribute]) ? $this->attributes[$attribute] : null;
        }

        /**
         * Returns node data.
         *
         * @return string
         */
        public function getData()
        {
            return $this->data;
        }

        /**
         * Sets node data.
         *
         * @param string $data
         */
        public function setData($data)
        {
            $this->data = $data;
        }

        /**
         * Returns count of nodes with current name.
         *
         * @return int
         */
        public function count()
        {
            return count($this->brothers);
        }

        /**
         * Returns node with current name in specified index.
         *
         * @param int $index
         * @return XmlNode
         */
        public function get($index)
        {
            return ($index < $this->count() ? $this->brothers[$index] : null);
        }

        /**
         * Adds node brother.
         *
         * @param XmlNode $brother
         */
        public function addBrother(XmlNode $brother)
        {
            $this->brothers[] = $brother;
        }

        /**
         * Converts xml node to array.
         *
         * @return array
         */
        public function toArray()
        {
            if ( count($this->brothers) == 1 )
            {
                return array( $this->getName() => $this->getData() );
            }

            $nodes = array();
            foreach ( $this->brothers as $brother )
            {
                $nodes[] = $brother->getData();
            }

            return array( $this->getName() => $nodes );
        }
    }

?>